<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="通道名称" prop="channelName">
            <el-input v-model="form.channelName" placeholder="请输入通道名称" :disabled="true"/>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="供应商" prop="providerId">
            <el-select v-model="form.providerId" placeholder="请选择供应商">
              <el-option v-for="(item, index) in allProviderList" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="归属省" prop="provinceCode">
            <el-select v-model="form.provinceCode" placeholder="请选择归属省">
              <el-option
                  v-for="item in allProvinceList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="屏蔽省" prop="hideProvinceName">
            <el-select
                v-model="form.hideProvinceName"
                placeholder="请选择屏蔽省"
                multiple
                filterable>
              <el-option
                  v-for="item in allProvinceList.filter(p => p.value !== '0')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="24" class="mb20">
          <el-form-item label="运营商" prop="ispCode">
            <el-select v-model="form.ispCode" placeholder="请选择运营商">
              <el-option
                  v-for="item in allIspList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="单价" prop="price">
            <el-input v-model="form.price" placeholder="请输入单价"/>
          </el-form-item>
        </el-col>


        <el-col :span="24" class="mb20">
          <el-form-item label="通道说明" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入通道说明"/>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option :value="parseInt(item.value)" :label="item.label" v-for="(item, index) in prov_provider_channel_status"
                         :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="敏感词" prop="sensitiveWord">
            <el-input v-model="form.sensitiveWord" placeholder="请输入敏感词"/>
          </el-form-item>
        </el-col>



        <el-col :span="24" class="mb20">
          <el-form-item label="扩展码长度限制" prop="extCodeLenLimit">
            <el-input v-model="form.extCodeLenLimit" placeholder="请输入扩展码长度限制"/>
          </el-form-item>
        </el-col>


      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="providerProviderChannelDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from "/@/hooks/message";
import {getObj, addObj, putObj} from '/@/api/bms/provider/providerChannel'
import {rule} from '/@/utils/validate';
import {allProviders} from "/@/api/bms/provider/provider";

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典 status字段转换成整形
const {prov_provider_channel_status} = useDict('prov_provider_channel_status')
// prov_provider_channel_status.value.forEach(item => {
//   item.value = Number(item.value)
// })
// console.log("prov_provider_channel_status",prov_provider_channel_status)
// 提交表单数据
const form = reactive({
  id: '',
  providerId: '',
  channelName: '',
  provinceCode: '',
  remark: '',
  ispCode: '',
  price: '',
  status: 1,
  sensitiveWord: '',
  hideProvinceName: '',
  extCodeLenLimit: '',
});
watch(
    () => [form.providerId, form.provinceCode, form.ispCode, form.price],
    () => {
      const provider = allProviderList.value.find(p => p.id == form.providerId);
      const isp = allIspList.find(p => p.value == form.ispCode);
      console.log(provider, form.provinceCode, isp, form.price)
      if (provider &&  form.provinceCode && isp && form.price) {
        form.channelName = `${provider.name}-${form.provinceCode}-${isp.label}-${form.price}元`;
      }
    },
    { deep: true }
);

// 定义校验规则
const dataRules = ref({
  providerId: [{required: true, message: '供应商id不能为空', trigger: 'blur'}],
  channelName: [{required: true, message: '通道名称不能为空', trigger: 'blur'}],
  provinceCode: [{required: true, message: '归属省不能为空', trigger: 'blur'}],
  remark: [{required: true, message: '通道说明不能为空', trigger: 'blur'}],
  ispCode: [{required: true, message: '运营商不能为空', trigger: 'blur'}],
  price: [{required: true, message: '单价不能为空', trigger: 'blur'}],
  status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
  extCodeLenLimit: [{required: true, message: '扩展码长度限制不能为空', trigger: 'blur'}],
})

//获取所有供应商
const allProviderList =  ref([]);
const getAllProviderList = async ()=>{
  const res = await  allProviders();
  allProviderList.value = res.data
}
//所有省份的列表,写死
const allProvinceList = [
  {label: '全国', value: '0'},
  {label: '北京', value: '11'},
  {label: '天津', value: '12'},
  {label: '河北', value: '13'},
  {label: '山西', value: '14'},
  {label: '内蒙古', value: '15'},
  {label: '辽宁', value: '21'},
  {label: '吉林', value: '22'},
  {label: '黑龙江', value: '23'},
  {label: '上海', value: '31'},
  {label: '江苏', value: '32'},
  {label: '浙江', value: '33'},
  {label: '安徽', value: '34'},
  {label: '福建', value: '35'},
  {label: '江西', value: '36'},
  {label: '山东', value: '37'},
  {label: '河南', value: '41'},
  {label: '湖北', value: '42'},
  {label: '湖南', value: '43'},
  {label: '广东', value: '44'},
  {label: '广西', value: '45'},
  {label: '海南', value: '46'},
  {label: '重庆', value: '50'},
  {label: '四川', value: '51'},
  {label: '贵州', value: '52'},
  {label: '云南', value: '53'},
  {label: '西藏', value: '54'},
  {label: '陕西', value: '61'},
  {label: '甘肃', value: '62'},
  {label: '青海', value: '63'},
  {label: '宁夏', value: '64'},
  {label: '新疆', value: '65'},
  {label: '台湾', value: '71'},
  {label: '香港', value: '81'},
  {label: '澳门', value: '82'}
];

const allIspList = [
  {label: '全网', value: 'ALL'},
  {label: '移动', value: 'CMCC'},
  {label: '联通', value: 'CUCC'},
  {label: '电信', value: 'CTCC'},
];

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
  getAllProviderList();
  // 获取provProviderChannel信息
  if (id) {
    form.id = id
    getProvProviderChannelData(id)
  }
};

// 提交
const onSubmit = async () => {
  // 转换屏蔽省格式为逗号分隔字符串
  if (Array.isArray(form.hideProvinceName)) {
    form.hideProvinceName = form.hideProvinceName.join(',');
  }

  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getProvProviderChannelData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    const data = res.data;
    // 将屏蔽省字符串转换为数组
    if (data.hideProvinceName && typeof data.hideProvinceName === 'string') {
      data.hideProvinceName = data.hideProvinceName.split(',');
    }
    Object.assign(form, data);
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});



</script>
